import 'dart:convert';

import 'package:get/get.dart';
import 'package:wk_robot2/app/blt/RobotCommandsHelper.dart';

import '../../../blt/protobuf/BleBindOrSwitchWifi.pb.dart';
import '../../../const/AppConst.dart';
import '../../../event/DataCallBack.dart';
import '../../../models/WifiInfo.dart';
import '../../../routes/app_pages.dart';
import '../../../widget/tips.dart';
import '../../bindtip/views/bindtip_view.dart';

class WifiSettingController extends GetxController {

  var wifiInfos = RxList<WifiInfo>();

  @override
  void onInit() {
    super.onInit();
    // 获取wifi列表数据.


  }

  @override
  void onReady() {
    super.onReady();
    RobotCommandsHelper().getWifiList(DataCallBack(
        deviceCallBack: (data) {
          BindOrSwitchWifiResponse wifiResponse = BindOrSwitchWifiResponse.fromBuffer(data[AppConst.BTL_DATA_KEY] as List<int>);
          print('wifi列表数据 ==========>2 ' + wifiResponse.data);
          Map wifiData = json.decode(wifiResponse.data);
          List<dynamic> childItems = json.decode(wifiData['p']);
          childItems.forEach((item) {
            WifiInfo wifiInfo = WifiInfo.fromJson(item);

            wifiInfos.add(wifiInfo);
          });

          print('wifi列表数据 ==========> wifiInfos.value length: ${this.wifiInfos.length}');


        }
    ));
  }

  @override
  void onClose() {
    super.onClose();
  }

  void configFreeWiFi(WifiInfo wifi) {
    Tips.showLoading();
    RobotCommandsHelper().configWifiList(wifi.c!, wifi.s!, '', DataCallBack(
        deviceCallBack: (data) {
          Tips.dismissLoading();
          BindOrSwitchWifiResponse wifiResponse = BindOrSwitchWifiResponse.fromBuffer(data[AppConst.BTL_DATA_KEY] as List<int>);
          print('wifi配置结果, ${wifiResponse.data}');
          Map wifiRepsonse = json.decode(wifiResponse.data);
          if(wifiRepsonse['co'] == 102) { //wifi联网成功.
            print('============> wifi联网成功');
            // 绑定机器人.
            Get.toNamed(Routes.BINDING);

          } else if(wifiRepsonse['co'] == -1) { //联网失败.
            Get.toNamed(Routes.BINDTIP,arguments: {
              'type': WIFI_UNVAILABLE_ERROR
            });



          }
        }
    ));
  }
}
